#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


"""Generate IE 7+ tests."""


__author__ = 'jasonstredwick@google.com (Jason Stredwick)'


import os
import re
import shutil

import file_format_convert
import ie7


def GenIE7(src_root='', dst_root=''):
  print 'Generate IE7 addon tests ...'

  js_root = os.path.join(src_root, ie7.JS_ROOT)
  test_root = os.path.join(src_root, ie7.TESTS_ROOT)

  # Prepare files
  dll = os.path.join(src_root, ie7.DLL)

  js_files = []
  for js_file in os.listdir(js_root):
    if re.match(r'^[.]', js_file) is None:
      js_files.append(os.path.join(js_root, js_file))

  test_targets = []
  for test in os.listdir(test_root):
    src = os.path.join(test_root, test)
    test_targets.append(src)

  # Ensure destination folder exists.
  tests_dst_root = os.path.join(dst_root, ie7.TESTS_ROOT)
  if not os.path.exists(tests_dst_root):
    os.makedirs(tests_dst_root)

  # Generate test bundles
  for test in test_targets:
    (_, test_name) = os.path.split(test)
    dst = os.path.join(tests_dst_root, test_name)
    shutil.copytree(test, dst)
    for js_file in js_files:
      shutil.copy2(js_file, dst)
    shutil.copy2(dll, dst)

    # Convert all html, css, and js files to windows format.
    cwd = os.getcwd()
    os.chdir(dst)
    files = os.listdir('.')
    for f in files:
      if re.search(r'[.](html|css|js|htm)', f) is not None:
        data = {
          'input': f,
          'output': f,
          'win': True
        }
        file_format_convert.Run(data)
    os.chdir(cwd)

  print '[SUCCESS] All tests generated.'
  print ''
